<?php

declare(strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class UserCreditRecord extends Model
{
  //

  public static function initCredit($user, $change_credit, $type, $desc = '', $is_save = true)
  {
    if (!$user instanceof User) {
      $user = User::find($user);
    }

    $model_record = new UserCreditRecord();

    $model_record->before_credit  = $user->getData('credit');
    $model_record->change_credit = $change_credit;
    $model_record->new_credit = $model_record->before_credit + $model_record->change_credit;

    
    $model_record->set('type',$type);

    $model_record->user_id = $user->id;
    $model_record->desc = $desc;

    if ($is_save) {
      return self::saveCredit($model_record, $user);
    }

    return $model_record;
  }

  public static function saveCredit(UserCreditRecord $model_record, User $user)
  {
    $user->credit = $model_record->new_credit;
    $user->total_credit = $model_record->before_credit + abs($model_record->change_credit);
    $user->save();

    $model_record->save();
    Vip::scanUser($user);
    return $model_record;
  }

  public static function optionCheckin($user, $times)
  {

    $base_credit = get_system_config('checkin_worth_credit', 0);

    $times_credit = get_system_config('checkin_times_worth_credit', 0) * ($times - 1);

    $total_credit = $base_credit + $times_credit;

    return self::initCredit($user, $total_credit, 'checkin', '连续签到' . $times . '次,获得' . $total_credit . '积分');
  }
}
